package com.hackathon.chgk.taskloaders.impl;

import java.sql.SQLException;
import java.util.List;

import android.util.Log;

import com.hackathon.chgk.ChgkApplication;
import com.hackathon.chgk.data.DatabaseHelper;
import com.hackathon.chgk.data.dao.Task;
import com.hackathon.chgk.taskloaders.TaskLoader;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;

public class OfflineTaskLoaderImpl implements TaskLoader {

	static final String CLASSNAME = OfflineTaskLoaderImpl.class.getName();
	
	public Task getRandomTask() {
		// TODO Auto-generated method stub
		return null;
	}

	public List<Task> getRandomTasks(int count) throws SQLException {
		List<Task> results = null;
		try {
			
			DatabaseHelper dbHelper = new DatabaseHelper(ChgkApplication.getInstance().getCurrentContext());
			//TODO: Should be limited by query
			
			QueryBuilder<Task, Integer> queryBuilder =
					dbHelper.getTaskDao().queryBuilder();
			queryBuilder.orderBy(Task.SHOWCOUNT_FIELD_NAME, true);			
			PreparedQuery<Task> preparedQuery = queryBuilder.prepare();
			results = dbHelper.getTaskDao().query(preparedQuery);

			results = results.subList(0, Math.min(results.size(), count));
			for(Task t : results) {
				Log.d("db_content", t.getHashCode()+": "+ t.getText());
			}
		} catch (SQLException e) {
			
			Log.e(OfflineTaskLoaderImpl.class.getName(),"Unable to load data from database");
			e.printStackTrace();
			throw e;
		}

		return results;
	}

}
